<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '@/views/dashboard/mixins/resize'
import {formatDate} from "@/utils";

export default {
  name: "LineComponent",
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
  },


  data(){
    return {
      chart: null,
      xAxisData: [],
      powerSeriesData: [],
      chargeSeriesData: [],
      timer: null,
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.initChart();
      this.startUpdatingData();
    })
  },

  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },

  methods: {
    // 初始化折线图
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');
      // option start -------------
      this.chart.setOption({
        title: {
          text: 'Power And Charge'
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.xAxisData
          }
        ],
        series: [
          {
            name: 'power',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: this.powerSeriesData
          },
          {
            name: 'charge',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: this.chargeSeriesData
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },

      });
      // option end -----------------

    },

    //开始变化
    startUpdatingData() {
      this.timer = setInterval(() => {
        const newTimestamp = this.formatNewDate(new Date().getTime());

        // 获取随机增量
        let newPower = Math.random() * 10;
        let newCharge = Math.random() * 10;
        let length = this.xAxisData.length;

        // 不为空,获取最后节点的值
        if(length !== 0){
          // power
          newPower += this.powerSeriesData[length-1];
          // charge
          newCharge += this.chargeSeriesData[length-1];

          this.powerSeriesData.push(newPower);
          this.chargeSeriesData.push(newCharge);
        }else{
          // 为空，添加初始值
          this.powerSeriesData.push(100);
          this.chargeSeriesData.push(50);
        }

        this.xAxisData.push(newTimestamp);

        if(this.xAxisData.length > 25){
          this.xAxisData.shift();
          this.powerSeriesData.shift();
          this.chargeSeriesData.shift();
        }

        this.chart.setOption({
          xAxis: {
            data: this.xAxisData
          },
          series: [
            {
              data: this.powerSeriesData
            },
            {
              data: this.chargeSeriesData
            }
          ]
        })
      },1000);
    },

    // 格式化时间
    formatNewDate(timestamp) {
      const date = new Date(timestamp);
      //const year = date.getFullYear();
      //const month = String(date.getMonth() + 1).padStart(2, '0');  月份是从0开始的，所以要加1
      //const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      // `${year}-${month}-${day} ${hours}:${minutes}:${seconds}

      return `${hours}:${minutes}:${seconds}`;
    }
  },


}

</script>

<style scoped>

</style>
